<script>
import { getElementTop } from "vant/lib/utils";
import { ref, onMounted, watch, defineEmits, nextTick } from "vue";
import { useRouter } from "vue-router";
import { gcj02towgs84 } from "../../../common/js/geoParser";
import gdBorder from "../../../static/images/gdBorder.json";
// import { getMarkPoint } from "../../../utils/apis";
import { getPos } from "../../../utils/bridgeAreaControlApi";
export default {
  setup() {
    const router = useRouter();
    const pointList = ref([]);
    let regionMark = new ol.source.Vector(); //区域中心点
    let regionMarkLayer = new ol.layer.Vector({
      source: regionMark,
    });
    // 地图坐标
    let projection = ol.proj.get("EPSG:4490");
    // 基础地图服务切片地址
    // let tileUrl = `http://210.76.81.180/traffic-channel/water_way/arcgis/rest/services/waterWayMap/gdhd22_tile/MapServer/tile/{z}/{y}/{x}`; //瓦片
    let tileUrl = `${
      import.meta.env.VITE_APP_BASE_API
    }water_way/arcgis/rest/services/waterWayMap/gdhd24_tile/MapServer/tile/{z}/{y}/{x}`; //瓦片
    // }/traffic-channel/water_way/arcgis/rest/services/waterWayMap/gdhd22_tile/MapServer/tile/{z}/{y}/{x}`; //瓦片

    // 坐标原点
    let origin = [-400.0, 399.9999999999998];
    let origin1 = [-180, 90];

    // 分辨率
    let resolutions = [
      0.010998658750001491, 0.005499329375000746, 0.002749664687500373,
      0.0013772106150255138, 6.875571549396887e-4, 3.437060039091665e-4,
      1.7185181222408033e-4, 8.592471638153725e-5, 4.296116846026571e-5,
      2.147939449962994e-5, 1.0738507519312054e-5, 5.368064029153112e-6,
      2.684032014576556e-6, 1.342016007288278e-6,
    ];

    let resolutions1 = [
      1.40625, 0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125,
      0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125,
      0.00137329101563, 0.00068664550781, 0.00034332275391, 0.00017166137695,
      0.00008583068848, 0.00004291534424, 0.00002145767212, 0.00001072883606,
      0.00000536441803, 0.00000268220901, 0.00000134110451,
    ];

    let resolutions2 = [
      1.4062499997204136, 0.7031249998602068, 0.3515625011198339,
      0.17578124937018644, 0.08789062468509322, 0.04394531353227711,
      0.021972656766138556, 0.010986328383069278, 0.005493164191534639,
      0.0027465809060368165, 0.0013732916427489112, 6.866458213744556e-4,
      3.433229106872278e-4, 8.582953794130404e-5, 4.291595870115493e-5,
      2.1457979350577466e-5, 1.0728989675288733e-5, 5.363305107141452e-6,
      2.681652553570726e-6, 1.342016007288278e-6,
    ];

    //地图范围
    //let fullExtent = [109.62468672071566, 20.061844971777152, 117.35435946391834, 25.519591749894282];

    let fullExtent = [-180, -90, 180, 90];
    //电子航道图
    let tileGrid = new ol.tilegrid.TileGrid({
      tileSize: 256,
      origin: origin,
      extent: fullExtent,
      resolutions: resolutions,
    });
    // 天地图
    let tileGrid1 = new ol.tilegrid.TileGrid({
      tileSize: 256,
      origin: origin1,
      extent: fullExtent,
      resolutions: resolutions1,
    });
    // 瓦片数据源
    let tileArcGISXYZ = new ol.source.XYZ({
      tileGrid: tileGrid,
      projection: projection,
      url: tileUrl,
    });

    // 瓦片图层-电子航道图
    let ArcMapLayer = new ol.layer.Tile({
      source: tileArcGISXYZ,
      visible: true,
      minZoom: 1, // 设置第一个图层的最小显示级别
      maxZoom: 18, // 设置第一个图层的最大显示级别
    });

    // 瓦片数据源--天地图
    let tileXYZ = new ol.source.XYZ({
      tileGrid: tileGrid1,
      projection: projection,
      // url: "http://210.76.81.180/traffic-channel/service/waterway/mapService/DayMapTile?tileMatrix={z}&tileRow={y}&tileCol={x}",
      url: `${
        import.meta.env.VITE_APP_BASE_API
      }service/waterway/mapService/DayMapTile?tileMatrix={z}&tileRow={y}&tileCol={x}`,
      // }/traffic-channel/pre-yth/bridge/small-screen/service/waterway/mapService/DayMapTile?tileMatrix={z}&tileRow={y}&tileCol={x}`,
    });

    // 瓦片图层--天地图
    let MapLayer = new ol.layer.Tile({
      source: tileXYZ,
      visible: true,
      minZoom: 1, // 设置第二个图层的最小显示级别
      maxZoom: 18, // 设置第二个图层的最大显示级别
    });

    let markTileXYZ = new ol.source.XYZ({
      tileGrid: tileGrid1,
      projection: projection,
      // url: "http://210.76.81.180/traffic-channel/service/waterway/mapService/getMapAnnotation?tileMatrix={z}&tileRow={y}&tileCol={x}",
      url: `${
        import.meta.env.VITE_APP_BASE_API
      }service/waterway/mapService/getMapAnnotation?tileMatrix={z}&tileRow={y}&tileCol={x}`,
      // }/traffic-channel/pre-yth/bridge/small-screen/service/waterway/mapService/getMapAnnotation?tileMatrix={z}&tileRow={y}&tileCol={x}`,
    });

    // 瓦片图层
    let markMapLayer = new ol.layer.Tile({
      source: markTileXYZ,
      visible: true,
    });

    //实例化ZoomToExtent
    let zoomToExtent = new ol.control.ZoomToExtent({
      extent: [
        //Todo 这个范围应该怎么确定
        13100000, 4290000, 13200000, 5210000,
      ],
    });

    const coordinates = gdBorder.features[0].geometry.coordinates[0][0];

    // 创建多边形实例
    const polygon = new ol.geom.Polygon([coordinates]);

    // 创建特征实例
    const feature = new ol.Feature(polygon);

    // 创建一个唯一的 id
    let layerId = "borderLayer";
    // 创建矢量图层实例
    const borderLayer = new ol.layer.Vector({
      id: layerId,
      source: new ol.source.Vector({
        features: [feature],
      }),
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(0, 0, 0, 0)",
        }),
        stroke: new ol.style.Stroke({
          color: "rgba(254, 223, 176,0.8)",
          width: 2,
          lineDash: [], // 画实线
        }),
      }),
    });
    borderLayer.set("name", "borderLayer");

    var selectedStyle = new ol.style.Style({
      fill: new ol.style.Fill({
        color: "rgba(255, 150, 45, 0)",
      }),
      stroke: new ol.style.Stroke({
        color: "rgba(254, 223, 176,0.8)",
        width: 2, // 设置边框宽度
        lineDash: [], // 画实线
      }),
    });
    const mapFlag = ref(true);
    const initMap = (data = {}) => {
      mapFlag.value = false;
      setTimeout(() => {
        mapFlag.value = true;
      }, 100);
      setTimeout(() => {
        let map = new ol.Map({
          target: "map",
          layers: [MapLayer, markMapLayer, borderLayer, ArcMapLayer],
          controls: ol.control.defaults({
            zoom: false, // 关闭缩放控件
          }),
          view: new ol.View({
            //初始化中心点坐标
            center: [113.359194, 22.745479],
            resolutions: resolutions1,
            // 注意：此处指定缩放级别不能通过zoom来指定，指定了也无效，必须通过resolution来指定
            // resolution: 0.02197265625,
            resolution: 0.00087265625,
            projection: projection,
            minZoom: 6,
            maxZoom: 18,
            extent: [-180, -90, 180, 90],
          }),
        });
        let selectSingleClick = new ol.interaction.Select(); //点击选择操作
        map.addInteraction(selectSingleClick);
        selectSingleClick.on("select", function (e) {
          let features = e.target.getFeatures().getArray();
          if (features.length > 0) {
            // 获取第一个选中的要素
            let selectedFeature = features[0];
            // 获取要素的属性
            let name = selectedFeature.get("name");
            let waterwayMileage = selectedFeature.get("waterwayMileage");
            let content;
            // 创建提示窗口内容
            content = `<div style="padding:6px;background: #000000;border-radius: 4px 4px 4px 4px;opacity: 0.8;color:white;font-weight: 500;"><div>${
              name || "--"
            }</div><div>所属航道：${waterwayMileage || "--"}</div></div>`;

            if (name != null && name != undefined) {
              let existingOverlay = map.getOverlayById("popup");
              if (existingOverlay) {
                // 如果已经存在的提示窗口，则更新内容和位置
                existingOverlay.setPosition(
                  selectedFeature.getGeometry().getCoordinates()
                );
                existingOverlay.getElement().innerHTML = content;
              } else {
                // 如果不存在提示窗口，则创建新的提示窗口
                let overlay = new ol.Overlay({
                  id: "popup",
                  element: document.createElement("div"),
                  positioning: "bottom-center",
                  stopEvent: false,
                });
                // selectedFeature 是一个地图上选定的要素（feature）， getGeometry() 是一个用于获得要素的几何信息的方法。getCoordinates() 是该要素几何图形的坐标属性，它返回一个包含要素位置信息的坐标数组。
                overlay.setPosition(
                  selectedFeature.getGeometry().getCoordinates()
                );
                overlay.getElement().innerHTML = content;
                map.addOverlay(overlay);
              }
            } else {
              let existingOverlay = map.getOverlayById("popup");
              if (existingOverlay) {
                map.removeOverlay(existingOverlay);
              }
            }
          } else {
            // 如果没有选中的要素，则移除提示窗口
            let existingOverlay = map.getOverlayById("popup");
            if (existingOverlay) {
              map.removeOverlay(existingOverlay);
            }
          }
        });

        regionMarkLayer.on("click", function (e) {
          let clickedCoordinate = e.coordinate;
          // 遍历所有图层
          let overlays = map.getOverlays().getArray();
          console.log(223, overlay.getElement());
          overlays.forEach(function (overlay) {
            if (overlay.getElement().contains(e.originalEvent.target)) {
              return;
            }
            if (!overlay.getElement().contains(e.originalEvent.target)) {
              map.removeOverlay(overlay);
            }
          });
        });

        getPos().then(async (res) => {
          getPos(data).then((highlight) => {
            pointList.value = [];
            regionMarkLayer
              .getSource()
              .getFeatures()
              .forEach(function (feature) {
                regionMarkLayer.getSource().removeFeature(feature);
              });
            if (res.code == 200) {
              res.data.map((el) => {
                if (
                  (el.lat != "" && el.lat != undefined && el.lat != null) ||
                  (el.lat != "" && el.lat != undefined && el.lat != null)
                ) {
                  // 设置点信息
                  let positionItem;
                  positionItem = {
                    position: [el.lng, el.lat],
                    num: el.num,
                    name: el.gcdMc,
                    waterwayMileage: el.bmPname,
                  };
                  pointList.value.push(positionItem);
                }
              });
              // console.log(highlight, pointList.value);
              // debugger;
              highlight.data.map((el) => {
                if (
                  (el.lat != "" && el.lat != undefined && el.lat != null) ||
                  (el.lat != "" && el.lat != undefined && el.lat != null)
                ) {
                  // 设置点信息
                  let positionItem;
                  positionItem = {
                    position: [el.lng, el.lat],
                    num: el.num,
                    name: el.gcdMc,
                    waterwayMileage: el.bmPname,
                    isHighlight: true,
                  };
                  pointList.value.push(positionItem);
                }
              });
              // console.log(pointList.value);
              // debugger;
              let isHighlightFalg = true;
              pointList.value.forEach((el) => {
                // 创建一个ol.Feature对象
                let anchor = new ol.Feature({
                  // 设置geometry属性,el.position点的位置信息
                  geometry: new ol.geom.Point(el.position),
                });
                anchor.setProperties({
                  name: el.name,
                  waterwayMileage: el.waterwayMileage,
                });
                if (el.isHighlight) {
                  if (isHighlightFalg) {
                    console.log(el.position);
                    setTimeout(() => {
                      map.getView().setCenter(el.position);
                    }, 300);
                    isHighlightFalg = false;
                  }
                  anchor.setStyle(
                    new ol.style.Style({
                      image: new ol.style.Icon({
                        src: new URL(
                          "../../../static/images/bridgeAreaControl/selected-marker.png",
                          import.meta.url
                        ).href,
                        scale: 0.03, // 设置图标的尺寸，1 表示原始尺寸
                      }),
                    })
                  );
                } else if (el.num < 5000) {
                  anchor.setStyle(
                    new ol.style.Style({
                      image: new ol.style.Icon({
                        src: new URL(
                          "../../../static/images/bridgeAreaControl/icon-xiaoyu5k.png",
                          import.meta.url
                        ).href,
                        scale: 1.2, // 设置图标的尺寸，1 表示原始尺寸
                      }),
                    })
                  );
                } else {
                  anchor.setStyle(
                    new ol.style.Style({
                      image: new ol.style.Icon({
                        src: new URL(
                          "../../../static/images/bridgeAreaControl/icon-dayu5k.png",
                          import.meta.url
                        ).href,
                        //  scale: 1.2, // 设置图标的尺寸，1 表示原始尺寸
                      }),
                    })
                  );
                }
                // 添加到之前的创建的layer中去
                regionMarkLayer.getSource().addFeature(anchor);
              });
            }
          });
        });

        map.addLayer(regionMarkLayer);
      }, 300);
    };
    onMounted(() => {
      // setTimeout(() => {
      //   initMap();
      // }, 100);
    });
    return {
      initMap,
      mapFlag
    };
  },
};
</script>
<template>
  <div class="main" v-if="mapFlag">
    <div id="map"></div>
    <div id="popup"></div>
  </div>
</template>

<style lang="scss" scoped>
.main {
  // position: relative;
  height: 100%;
  overflow: hidden;
  #map {
    // width: 375px;
    width: 100%;
    height: 100%;
  }
}
</style>
